import json
import random


class Room:
    def __init__(self, maximum, server, roomid):
        self.players = [None] * maximum
        self.board = []
        self.pnum = 0
        self.maximum = maximum
        self.server = server
        self.roomid = roomid
        self.gaming = False
        self.next = 0

    async def sendall(self, data, withid=False):
        for i in range(self.maximum):
            s = self.players[i]
            if s is None:
                continue
            if withid:
                data["pid"] = i
            try:
                await s.send(json.dumps(data))
            except Exception as e:
                print("发送失败" + str(i))
                pass

    def destroy(self):
        self.gaming = False
        self.server.delRoom(self.roomid)

    async def join(self, player):
        if self.gaming:
            return None
        if self.pnum == self.maximum:
            return None
        self.pnum += 1
        pid = None
        for i in range(self.maximum):
            if self.players[i] is None:
                pid = i
                self.players[i] = player
                break
        if self.pnum == self.maximum:
            self.gaming = True
            await self.start()
        else:
            await self.sendall({"command": "wait", "num": self.pnum})
        return pid

    async def chat(self, pid, data):
        message = data['message']
        if "阔" in message:
            message = "@all，有人发送了一条含阔的消息： " + message
        await self.sendall({"command": "chat", "pid": pid, "message": message})

    async def win(self, pid):
        await self.sendall({"command": "win", "pid": pid})
        self.destroy()

    async def giveup(self, pid, data):
        if self.gaming:
            await self.sendall({"command": "giveup", "pid": pid})
            self.destroy()

    async def leave(self, pid):
        self.players[pid] = None
        self.pnum -= 1
        if self.gaming:
            await self.sendall({"command": "leave", "pid": pid})
            self.destroy()
        else:
            await self.sendall({"command": "wait", "num": self.pnum})

    async def start(self):
        pass

    async def act(self, pid, data):
        pass


base = {"chat": Room.chat, "givup": Room.giveup}
funs = {}


def add(fun):
    c, n = fun.__qualname__.split(".")
    c = c.lower()
    if funs.get(c) is None:
        funs[c] = base.copy()
    funs[c][n] = fun


from rooms import ddz, wzq

Rooms = {"ddz": ddz.Ddz, "wzq": wzq.Wzq}
